package com.bt.springboot.common.util;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转换为拼音
 * @author zkx
 * @Date 2023/1/29 14:30
 */
@Slf4j
public class PinyinUtil {

	/**
	 * 测试main方法
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("‘张三’首字母大写：" + toFirstChar("whmj10143@sina.com")); //转为首字母大写
		System.out.println("‘张三’转成拼音：" + toPinyin("张三"));
	}
	/**
	 * 获取字符串拼音的第一个字母
	 * @param chinese
	 * @return
	 */
	public static String toFirstChar(String chinese){
		// 去掉特殊符号
		chinese = chinese.replaceAll("[）（—\\-+^:,]","");
		StringBuilder pinyinStr = new StringBuilder();
		char[] newChar = chinese.toCharArray();  //转为单个字符
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (char c : newChar) {
			if (c > 128) {
				try {
					pinyinStr.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0].charAt(0));
				} catch (Exception e) {
					log.error("error in {}",chinese, e);
				}
			} else {
				pinyinStr.append(c);
			}
		}
		return pinyinStr.toString();
	}

	/**
	 * 汉字转为拼音
	 * @param chinese
	 * @return
	 */
	public static String toPinyin(String chinese){
		StringBuilder pinyinStr = new StringBuilder();
		char[] newChar = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (char c : newChar) {
			if (c > 128) {
				try {
					pinyinStr.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pinyinStr.append(c);
			}
		}
		return pinyinStr.toString();
	}
}
